#include "../lib/speaker.hpp"
#include <sys/poll.h>
#include <unistd.h>
#include <sys/time.h>

using namespace kport;
using pland::utill_log;
using pland::utill_to_string;
using pland::Exeption;

Speaker::Speaker(int sock, pland::SharedDQueue qin)
{
    sock_ = sock;
    qin_ = qin;
}

Speaker::~Speaker()
{
    ::close(sock_);
}

bool Speaker::ready() throw(pland::Exeption)
{
    if(qin_->is_empty())
        return false;
    return true;
}

WorkItemStat Speaker::work() throw(pland::Exeption)
{
    int status;
    pland::SharedData item = qin_->pop();
    status = pland::utill_io_write(sock_, (char*)(item->get_header()), sizeof(pland::Data_Header));
	if(status != sizeof(pland::Data_Header))
    {
        utill_log(std::string(__FILE__) + " KPort Listener data recieve failed. Errno " + utill_to_string(errno));
		throw Exeption("Write system call failed", PEXP_FATAL);
    }
    status = pland::utill_io_write(sock_, (char*)(item->get_data()), item->get_header()->size);
	if(status != item->get_header()->size)
	{
		utill_log(std::string(__FILE__) + " KPort Listener data recieve failed. Errno " + utill_to_string(errno));
		throw Exeption("Write system call failed", PEXP_FATAL);
	}

    WorkItemStat ret;

    struct timeval now;
    gettimeofday(&now, NULL);
    ret.secTime = now.tv_sec;
    ret.usecTime = now.tv_usec;

    int64_t usecLatency = (now.tv_sec - item->get_header()->secLocal)*1e6  + now.tv_usec - item->get_header()->usecLocal;
    ret.secLatency = usecLatency / 1000000;
    ret.usecLatency = usecLatency % 1000000;
    ret.bytes = sizeof(pland::Data_Header) + item->get_header()->size;
    ret.items = 1;
    return ret;
}
